package com.terry.trace.core.util;

import com.terry.trace.core.constant.DatePatternConstant;

import java.util.Date;
import java.util.Random;

/**
 * ID生成器
 * @author TerryJiang
 */
public class IdGenerator {

    /**
     * flowNo随机数部分的长度
     */
    private static final int FLOW_NO_RANDOM_NUM_LENGTH = 10;

    /**
     * 生成flowNo
     * @return
     */
    public static String generateFlowNo() {
        String dateStr = DateUtils.format(new Date(), DatePatternConstant.PURE_DATETIME_MS_PATTERN);
        String randomStr = genRandomNum(FLOW_NO_RANDOM_NUM_LENGTH);
        return dateStr + randomStr;
    }

    /**
     * 生成指定长度的随机数
     * @param length
     * @return
     */
    public static String genRandomNum(int length) {
        final int maxNum = 36;
        int i;
        int count = 0;
        char[] str = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

        StringBuilder result = new StringBuilder();
        Random r = new Random();
        while (count < length) {
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                result.append(str[i]);
                count++;
            }
        }
        return result.toString();
    }
}
